<?php

namespace app\shop\model\proxy;

use app\common\model\proxy\User as UserModel;
use app\shop\model\product\Product as ProductModel;
use app\shop\model\proxy\Region as RegionModel;
use app\shop\model\region\Region;

class User extends UserModel
{


    public function getRegions()
    {
        return RegionModel::getRegions($this["proxy_id"]);
    }

    public function regions()
    {
        return $this->hasMany(RegionModel::class, 'proxy_id', 'proxy_id')
            ->where('is_delete', '=', '0')
            ->field(["proxy_region_id", "proxy_id", "region_id"]);
    }

    public function getList($params)
    {
        $model = $this;
        if (!empty($params['search'])) {
            $model = $model->where(function ($query) use ($params) {
                $query->where('name', 'like', '%' . $params['search'] . '%')->whereOr('mobile', 'like', '%' . $params['search'] . '%');
            });
        }
        // 查询列表数据
        return $model->where('is_delete', '=', '0')
            ->order(['create_time' => 'desc'])
            ->with("regions")
            ->withoutField(["password"])
            ->paginate($params);
    }


    public function add($data)
    {
        $this->startTrans();
        try {
            $proxy = $data['proxy'];
            if (UserModel::checkExist($proxy['user_name'])) {
                $this->error = '用户名已存在';
                return false;
            }
            if (UserModel::checkExist($proxy['mobile'], "mobile")) {
                $this->error = '手机号已存在';
                return false;
            }
            $regions = $proxy["regions"] ?? [];
            if (empty($regions)) {
                $this->error = '请设置代理地区';
                return false;
            }
            foreach ($regions as $region) {
                end($region);
//                $check = db("proxy_region")->where("region_id", current($region))->where("is_delete", 0)->value("proxy_region_id");
                $region_id = current($region);
                if (RegionModel::checkExist($region_id)) {
                    $this->error = sprintf("[%s]已设置代理", Region::getMergerName($region_id));
                    return false;
                }
            }
            unset($proxy["regions"]);
            $proxy['password'] = salt_hash($proxy['password']);
            $proxy['app_id'] = self::$app_id;
            $this->save($proxy);
            foreach ($regions as $region) {
                end($region);
                $region_id = current($region);
                $regionModel = new RegionModel();
                $regionModel->save([
                    "province_id" => $region[0],
                    "city_id" => $region[1] ?? 0,
                    "county_id" => $region[2] ?? 0,
                    "region_id" => $region_id,
                    "level" => count($region),
                    "proxy_id" => $this["proxy_id"],
                    'app_id' => self::$app_id,
                ]);
            }
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }

    }

    public function edit($data)
    {
        // 开启事务
        $this->startTrans();
        try {
            $proxy = $data['proxy'];
            if (UserModel::checkExist($proxy['mobile'], "mobile", $this["proxy_id"])) {
                $this->error = '手机号已存在';
                return false;
            }

            $regions = $proxy["regions"] ?? [];
            if (empty($regions)) {
                $this->error = '请设置代理地区';
                return false;
            }
            foreach ($regions as $region) {
                end($region);
                $region_id = current($region);
                if (RegionModel::checkExist($region_id, $this["proxy_id"])) {
                    $this->error = sprintf("[%s]已设置代理", Region::getMergerName($region_id));
                    return false;
                }
            }
            unset($proxy["regions"]);
            $proxy['password'] = $proxy['password'] ? salt_hash($proxy['password']) : $this["password"];
            $proxy['app_id'] = self::$app_id;
            $this->save($proxy);
            $regionModel = new RegionModel();
            $regionModel->update(["is_delete" => 2], ["proxy_id" => $this["proxy_id"]]);
            foreach ($regions as $region) {
                end($region);
                $region_id = current($region);
                $data = [
                    "province_id" => $region[0],
                    "city_id" => $region[1] ?? 0,
                    "county_id" => $region[2] ?? 0,
                    "region_id" => $region_id,
                    "level" => count($region),
                    "proxy_id" => $this["proxy_id"],
                    'app_id' => self::$app_id,
                    'is_delete' => 0
                ];
                $find = $regionModel->where([
                    "region_id" => $region_id,
                    "proxy_id" => $this["proxy_id"],
                    'app_id' => self::$app_id
                ])->find();
                if ($find) {
                    $data["proxy_region_id"] = $find["proxy_region_id"];
                    $find->save($data);
                } else {
                    $regionModel->save($data);
                }
            }
            $regionModel->update(["is_delete" => 1], ["proxy_id" => $this["proxy_id"], "is_delete" => 2]);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    public function setRecycle($status)
    {
        // 开启事务
        $this->startTrans();
        try {
            $this->save(['status' => $status]);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    /**
     * 软删除
     */
    public function setDelete()
    {

        $this->startTrans();
        $regionModel = new RegionModel();
        try {
            $regionModel->update(["is_delete" => 1], ["proxy_id" => $this["proxy_id"]]);
            $this->save(['is_delete' => 1]);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }
}